package web.controllers;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelovectorial.core.SearchEngine;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * @project DLC Final / UTN FRC 2013
 * @date Febrero de 2013
 *
 * @author Gonzalo Arribere
 * @author Gustavo Morales
 * @author Pablo Moreno
 */

public class PublishController extends HttpServlet
{
    private final String REPLACES[][] = {{"Ã¡", "Ã©", "Ã­", "Ã³", "Ãº", "Ã±", "Ã‘", "Ã‰", "Ã“", "Ãš"}, {"á", "é", "í", "ó", "ú", "ñ", "Ñ", "É", "Ó", "Ú"}};
    private String mWorkDirectory;

    @Override
    public void init (ServletConfig config)
    {
        mWorkDirectory = config.getServletContext ().getRealPath ("/pdf").replace ("build\\web\\", "");
    }
    public String fixFileName (String pBadFileName)
    {
        int i;
        for (i = 0; i < REPLACES[0].length; i++)
        {
            pBadFileName = pBadFileName.replace (REPLACES[0][i], REPLACES[1][i]);
        }
        return pBadFileName;
    }
    public boolean uploadFile (HttpServletRequest pRequest)
    {
        try
        {
            // construimos el objeto que es capaz de parsear la perición
            if (ServletFileUpload.isMultipartContent (pRequest))
            {
                ServletFileUpload upload = new ServletFileUpload (new DiskFileItemFactory ());

                List fileItems = upload.parseRequest (pRequest);

                if (fileItems == null)
                {
                    return false;
                }

                if (fileItems.size () == 1)
                {
                    Iterator i = fileItems.iterator ();
                    FileItem actual = null;

                    if (i.hasNext ())
                    {
                        actual = (FileItem) i.next ();
                        if (actual.getFieldName ().compareTo ("pdf") == 0)
                        {
                            String fileName = fixFileName (actual.getName ());

                            // construimos un objeto file para recuperar el trayecto completo
                            File fichero = new File (fileName);

                            fichero = new File (mWorkDirectory + File.separator + fichero.getName ());
                            pRequest.setAttribute ("file_uploaded", fichero.getName ());

                            if (!fichero.exists ())
                            {
                                actual.write (fichero);
                            }
                            else
                            {
                                return false;
                            }

                        }
                    }
                }
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

    protected void processRequest (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        
        if (uploadFile (request))
        {
            SearchEngine searchEngine = new SearchEngine ();
            System.out.println ("---------FILE::::::: " + request.getAttribute ("file_uploaded"));
            searchEngine.IndexFile (mWorkDirectory, (String) request.getAttribute ("file_uploaded"));

            RequestDispatcher dispatcher = request.getRequestDispatcher (SitePages.PAGE_UPLOAD_SUCCESS);
            dispatcher.forward(request, response);
        }
        else
        {
            if (request.getAttribute ("file_uploaded") != null)
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher (SitePages.PAGE_UPLOAD);
                dispatcher.forward(request, response);
            }
            else
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher (SitePages.PAGE_UPLOAD);
                dispatcher.forward(request, response);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest (request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest (request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo ()
    {
        return "Short description";
    }// </editor-fold>
}
